<template>
  <div class="chat-container">
    <div v-for="(msg, index) in messages" :key="index" class="message">
      <div :class="msg.role">{{ msg.content }}</div>
    </div>
    <input v-model="inputText" @keyup.enter="sendMessage" />
    <button @click="sendMessage">发送</button>
  </div>
</template>

<script setup lang="ts">
import {onUnmounted, ref} from 'vue';

interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}

const inputText = ref('');
const messages = ref<ChatMessage[]>([]);
let eventSource: EventSource | null = null; // 改用 EventSource

const sendMessage = async () => {
  if (!inputText.value.trim()) return;

  // 添加用户消息
  messages.value.push({ role: 'user', content: inputText.value });
  const userMessage = inputText.value;
  inputText.value = '';

  // 初始化助手消息
  messages.value.push({ role: 'assistant', content: '' });

  try {
    // 关闭已有连接（防止重复）
    if (eventSource) {
      eventSource.close();
    }

    // 使用 EventSource 代替 fetch
    eventSource = new EventSource(`http://localhost:8080/api/stream?prompt=${encodeURIComponent(userMessage)}`);

    eventSource.onmessage = (event) => {
      // ✅ 正确解析：event.data 已自动过滤 data: 前缀
      messages.value[messages.value.length - 1].content += event.data;
    };

    eventSource.onerror = (err) => {
      console.error('SSE Error:', err);
      eventSource?.close();
      // messages.value[messages.value.length - 1].content += '\n（连接异常）';
    };

  } catch (err) {
    console.error('请求失败:', err);
    messages.value[messages.value.length - 1].content += '\n（服务异常）';
  }
};

// 组件卸载时关闭连接
onUnmounted(() => {
  eventSource?.close();
});
</script>

<style>
.chat-container { /* 样式... */ }
.user { color: blue; }
.assistant { color: green; }
</style>